from datetime import datetime

from flask import jsonify, request

from aab import app
from aab.handlers_auth import create_user
from aab.model import Publication, db, User, Roles
from aab.utils import success, login_required, jsonify_error


@app.route('/announce/latest', methods=['GET'])
@login_required
def query_announce():
    announce = Publication.query.order_by(Publication.publish_time.desc()).first()
    if announce is None:
        result = {
            'content': '',
            'publish_time': None
        }
    else:
        result = announce.to_dict()
    return jsonify(result)


@app.route('/announces', methods=['POST'])
@login_required(roles=[Roles.ADMIN])
def add_announce():
    data = request.get_json()
    if data is None:
        return jsonify_error(400, message='Require JSON data')

    p = Publication().update_from_dict(data)
    p.publish_time = datetime.now()
    db.session.add(p)
    db.session.commit()
    return success()


@app.route('/init-db')
def init_db():
    db.create_all()
    admin = 'admin'
    user = User.query.filter_by(number=admin).scalar()
    if user is None:
        create_user(admin, admin, Roles.ADMIN)
        db.session.commit()

    return success()


@app.route('/config')
@login_required(roles=[Roles.ADMIN])
def query_config():
    # d = config.to_dict(encode_json=True)
    return jsonify([])


